package com.jk.controller;

import com.jk.controller.util.ConstantLYG;
import com.jk.controller.util.ExcelToolLYG;
import com.jk.pojo.PayLog;
import com.jk.pojo.PayUser;
import com.jk.service.PayLogServiceLiyg;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 交易记录操作
 */
@RestController
@RequestMapping("app/pay")
public class PayLogController {
    @Autowired
    private PayLogServiceLiyg payLogServiceLiyg;

    /**
     *  交易记录查询（√）
     */
    @GetMapping("queryPayLogList")
    public List<PayLog> queryPayLogList(PayLog payLog,HttpServletRequest request) throws ParseException {
        //获取前台传来的数据
        String logTime = request.getParameter("logTime");
        String logType = request.getParameter("logType");
        //获取session中登陆的userId
        PayUser us = (PayUser) request.getSession().getServletContext().getAttribute("us");
        //把获取到的值给PayLog
        if (logTime!=null&&logTime!=""){
            SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd");
            Date logDate = sim.parse(logTime);
            payLog.setSaveTime(logDate);
        }
        if (logType!=null&&logType!=""){
            payLog.setLogType(Integer.parseInt(logType));
        }
        String userId = us.getUserid();
        payLog.setUserId(userId);
        payLog.setPage(1);
        payLog.setRows(10); //默认10条
        //调用方法计算出开始位置和结束位置
        payLog.calculate();
        //根据开始位置和结束位置查询交易记录
        System.out.println(payLog);
        List<PayLog> payLogsList = payLogServiceLiyg.queryPayLogList(payLog);
        return payLogsList;
    }
    /**
     * 交易记录逻辑删除（√）
     */
    @PutMapping("updateDelete")
    public String updateDelete(HttpServletRequest request){
        //获取前台传来的值
        String logId = request.getParameter("logId");
        //根据参数进行逻辑删除
        boolean isOk = payLogServiceLiyg.updateDelete(logId);
        String  flag = "";
        if (isOk == true) {
            flag = "删除成功";
        }else{
            flag = "删除失败";
        }
        return flag;
    }
    /**
     * 统计金额---------------------------------------------------------------------------
     */
    /**
     * 下载账单（poi导出）
     */
    @GetMapping("billDownloadingByThread")
    public void billDownloadingByThread(HttpServletResponse response){
        System.out.println("成功进入方法");
        XSSFWorkbook wb = new XSSFWorkbook();
        //调用分页方法查询数据并获取总条数 第一次获取第一页数据
        Map map = payLogServiceLiyg.billDownloadingByThread(ConstantLYG.EXPROT_PAGE_START, ConstantLYG.EXPROT_PAGE_SIZE);
        //获取到分页数据的总条数
        int  totalCount = (Integer) map.get("total");
        //根据总条数计算出总页数
        int totalPage = totalCount%ConstantLYG.EXPROT_PAGE_SIZE==0?totalCount/ConstantLYG.EXPROT_PAGE_SIZE:(totalCount/ConstantLYG.EXPROT_PAGE_SIZE)+1;
        //创建线程池
        ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
        //线程执行计数器 需要创建多少线程就传递线程创建数量
        CountDownLatch doneSignal = new CountDownLatch(totalPage);
        //创建一个多线程 把第一页数据导出
        XSSFSheet sheetFirst = wb.createSheet();
        //第一次分页查询出的数据创建线程开始导出
        List dataFirst = (List) map.get("rows");
        singleThreadExecutor.execute(new ExcelToolLYG(sheetFirst,dataFirst,PayLog.class,doneSignal));
        //查询出数据库总的总条数 为批量导出设置导出长度
        for (int i = 2; i <= totalPage; i++) {
            XSSFSheet sheet = wb.createSheet();
            Map dataMap = payLogServiceLiyg.billDownloadingByThread(i, ConstantLYG.EXPROT_PAGE_SIZE);
            //每次循环创建一个子线程 execute相当于thread类中的start方法
            singleThreadExecutor.execute(new ExcelToolLYG(sheet,(List)dataMap.get("rows"),PayLog.class,doneSignal));
        }
        //获取到response输出流
        ServletOutputStream outputStream = null;
        try {
            //判断当前计数器是否为0 为零则放过主线程继续执行 不为0 则锁定当前主线程不执行
            doneSignal.await();
            //线程池使用完毕之后关闭线程池
            singleThreadExecutor.shutdown();
            response.addHeader("Content-Disposition", "attachment;fileName=" + "temp.xlsx");// 设置文件名
            outputStream = response.getOutputStream();
            wb.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if(outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * 回收站查询（√）
     */
    @GetMapping("queryRecycleList")
    public List<PayLog> queryRecycleList(PayLog payLog,HttpServletRequest request){
        //获取session中登陆的userId
        PayUser us = (PayUser) request.getSession().getServletContext().getAttribute("us");
        //把获取到的值给PayLog
        String userId = us.getUserid();
        payLog.setUserId(userId);
        payLog.setPage(1);
        payLog.setRows(10); //默认10条
        //调用方法计算出开始位置和结束位置
        payLog.calculate();
        //根据开始位置和结束位置查询回收站交易记录
        List<PayLog> RecycleList = payLogServiceLiyg.queryRecycleList(payLog);
        return RecycleList;
    }
    /**
     * 回收站物理批量删除（√）
     */
    @DeleteMapping("deleteRecycleList")
    public String deleteRecycleList(String ids){
        //获取前台传来的值
        //String ids=request.getParameter("ids");
        //根据参数进行批量删除或者单个删除
        boolean isOk = payLogServiceLiyg.deleteRecycleList(ids);
        String  flag = "";
        if (isOk == true) {
            flag = "永久删除成功";
        }else{
            flag = "删除失败";
        }
        return flag;
    }

    /**
     * 回收站数据批量还原
     */
    @PutMapping("updateReduction")
    public String updateReduction(PayLog payLog, HttpServletRequest request){
        //获取前台传来的值
        String ids = request.getParameter("ids");
        //根据参数进行批量还原
        boolean isOk = payLogServiceLiyg.updateReduction(ids);
        String  flag = "";
        if (isOk == true) {
            flag = "还原成功";
        }else{
            flag = "还原失败";
        }
        return flag;
    }


}
